#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

class Request
{
public:
    Request(int begin, int end, const string& threadname)
    :_begin(begin),_end(end), _threadname(threadname)
    {}

public:
    int _begin;
    int _end;
    string _threadname;
};

class Response
{
public:
    Response(int res, int exitcode)
    :_res(res), _exitcode(exitcode)
    {}

public:
    int _res;
    int _exitcode;
};

void *countSum(void *args)
{
    Request *rq = static_cast<Request*>(args); //  Request *rq = (Request*)args
    Response *rsp = new Response(0,0);
    for(int i = rq->_begin; i <= rq->_end; i++)
    {
        cout << rq->_threadname << " is runing, caling..., " << i << endl;
        rsp->_res += i;
        usleep(100000);
    }
    delete rq;
    return rsp;
}

int main()
{
    pthread_t tid;
    Request* rqp = new Request(1,100,"thread 1");
    pthread_create(&tid,nullptr,countSum,rqp);

    void *ret;
    pthread_join(tid,&ret);

    Response *rsp = static_cast<Response *>(ret);
    cout << "rsp->result: " << rsp->_res << ", exitcode: " << rsp->_exitcode << endl;
    delete rsp;
    return 0;
}

// void *threadRun(void* args)
// {
//     int cnt = 5;
//     while(cnt)
//     {
//         cout << "I am new thread my pid is : " << getpid() << endl;
//         sleep(1);
//         cnt--;
//     }
//     exit(11);
//     //return (void*)1;
// }

// int main()
// {
//     pthread_t tid;
//     pthread_create(&tid,nullptr,threadRun,nullptr);
    
//     // while(1)
//     // {
//     //     cout << "I am main thread my pid is : " << getpid() << endl;
//     //     sleep(1);
//     // }

//     void *retval;
//     pthread_join(tid,&retval);//main thread等待的时候，默认是阻塞等待的。
//     //为什么Join的时候不考虑异常？因为做不到，当线程异常其实就是主线程异常
//     cout << "main thread quit~ retval : " << (long long int) retval << endl;
//     return 0;
// }